<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="仓库编码" prop="code">
        <el-input placeholder="请输入仓库编码" v-model="queryParams.code" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="仓库名称" prop="name">
        <el-input placeholder="请输入仓库名称" v-model="queryParams.name" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="仓库类型" prop="type">
        <el-select v-model="queryParams.type" clearable @keyup.enter.native="handleQuery">
          <el-option label="全部" value=""/>
          <el-option label="原材料仓" value="1"/>
          <el-option label="成品仓" value="2"/>
          <el-option label="半成品仓" value="3"/>
          <el-option label="废品仓" value="4"/>
        </el-select>
      </el-form-item>
      <el-form-item label="仓库位置" prop="location">
        <el-input placeholder="请输入仓库位置" v-model="queryParams.location" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="仓库状态" prop="status">
        <el-select v-model="queryParams.status" clearable @keyup.enter.native="handleQuery">
          <el-option label="全部" value=""/>
          <el-option label="启用" value="1"/>
          <el-option label="停用" value="0"/>
        </el-select>
      </el-form-item>
      <el-form-item label="仓库管理员" prop="managerId" label-width="90px">
        <!--        <el-select>-->
        <!--          <el-option></el-option>-->
        <!--        </el-select>-->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['storage:warehouse:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['storage:warehouse:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['storage:warehouse:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['storage:warehouse:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-table v-loading="loading" :data="warehouseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="仓库编码" align="center" prop="code"/>
      <el-table-column label="仓库名称" align="center" prop="name"/>
      <el-table-column label="仓库类型" align="center" prop="type" :formatter="formatWarehouseType"/>
      <el-table-column label="仓库位置" align="center" prop="location"/>
<!--      <el-table-column label="仓库管理员" align="center" prop="managerId" :formatter="formatWarehouseAdmin"/>-->
      <el-table-column label="状态" align="center" prop="status" :formatter="formatWarehouseStatus"/>
      <el-table-column label="详细数据" type="expand" width="100px" align="center">
        <template #default="props">
          <table style="margin: auto 50px; width: 100%; border-collapse: collapse;">
            <tr>
              <td style="width: 50%; vertical-align: top; padding: 8px;">
                <b>备注：</b>{{ props.row.remark }}<br>
                <b>创建时间：</b>{{ props.row.createdAt }}<br>
                <b>更新时间：</b>{{ props.row.updatedAt }}<br>
                <b>仓库总储位：</b>{{ props.row.capacity }}<br>
                <b>仓库已使用储位：</b>待计算（已使用：？%）<br>
                <b>仓库库区数量：</b>待计算<br>
                <b>总物料数量：</b>待计算
              </td>
              <td style="width: 50%; vertical-align: top; padding: 8px;">
                <b>库区列表：</b>
                <br>
                <div style="margin-top: 5px;">
                  <ul>
                    <li v-for="area in props.row.storageAreaList.data" :key="area.id">
                      <router-link :to="{name: 'Area'}" style="color: #00afff">
                        {{area.name}}
                      </router-link>
                    </li>
                  </ul>
                </div>
              </td>
            </tr>
          </table>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['storage:warehouse:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['storage:warehouse:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>

    </el-table>


    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改仓库基础信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="仓库编码" prop="code" label-width="100px">
          <el-input v-model="form.code" placeholder="请输入仓库编码"/>
        </el-form-item>
        <el-form-item label="仓库名称" prop="name" label-width="100px">
          <el-input v-model="form.name" placeholder="请输入仓库名称"/>
        </el-form-item>
        <el-form-item label="仓库类型" prop="type" label-width="100px">
          <el-select v-model="form.type">
            <el-option label="原材料仓" :value="1"/>
            <el-option label="成品仓" :value="2"/>
            <el-option label="半成品仓" :value="3"/>
            <el-option label="废品仓" :value="4"/>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库位置" prop="location" label-width="100px">
          <el-input v-model="form.location" placeholder="请输入仓库位置"/>
        </el-form-item>
        <el-form-item label="仓库状态" prop="status" label-width="100px">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="仓库管理员" prop="managerId" label-width="100px">
          <el-select v-model="form.managerId" placeholder="请选择仓库管理员">
            <el-option label="张三" :value="1"/>
            <el-option label="李四" :value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库总储位" prop="capacity" label-width="100px">
          <el-input-number v-model="form.capacity"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark" label-width="100px">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listWarehouse,
  getWarehouse,
  delWarehouse,
  addWarehouse,
  updateWarehouse,
  getErpStorageArea, getErpWarehouseAndArea
} from "@/api/storage/warehouse"
import Index from "@/views/index.vue";
import Operlog from "@/views/monitor/operlog/index.vue";

export default {
  name: "Warehouse",
  components: {Operlog, Index},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓库基础信息表格数据
      warehouseList: [
        {
          // 库区信息表格数据
          storageAreaList: [],
        }
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        type: null,
        location: null,
        status: null,
        managerId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          {required: true, message: "仓库编码不能为空", trigger: "blur"},
          {min: 5, max: 20, message: "长度在5到10个字符", trigger: "blur"},
        ],
        name: [
          {required: true, message: "仓库名称不能为空", trigger: "blur"},
        ],
        type: [
          {required: true, message: "仓库类型不能为空", trigger: "blur"},
        ],
        location: [
          {required: true, message: "仓库位置不能为空", trigger: "blur"},
        ],
        status: [
          {required: true, message: "仓库状态不能为空", trigger: "blur"},
        ],
        managerId: [
          {required: true, message: "仓库管理员不能为空", trigger: "blur"},
        ],
        capacity: [
          {required: true, message: "仓库总储位不能为空", trigger: "blur"},
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 格式化仓库类型显示
    formatWarehouseType(row) {
      const typeMap = {
        1: '原材料仓', 2: '成品仓', 3: '半成品仓', 4: '废品仓'
      };
      return typeMap[row.type] || row.type;
    },
    // 格式化仓库管理员显示
    formatWarehouseAdmin(row) {
      const adminMap = {
        1: '张三', 2: '李四', 3: '王五', 4: '老六'
      };
      return adminMap[row.managerId] || row.managerId;
    },
    // 格式化仓库状态显示
    formatWarehouseStatus(row) {
      const statusMap = {
        0: '停用', 1: '启用'
      };
      return statusMap[row.status] || row.type;
    },

    /** 查询仓库基础信息列表 */
    getList() {
      this.loading = true
      listWarehouse(this.queryParams).then(response => {
        this.warehouseList = response.rows
        this.total = response.total

        // 遍历仓库id来查询每个库区的信息
        this.warehouseList.map(warehouse =>
          getErpStorageArea(warehouse.id).then(areaRes => {
            warehouse.storageAreaList = areaRes;
          })
        );

        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        type: null,
        location: null,
        managerId: null,
        status: null,
        capacity: null,
        remark: null,
        createdAt: null,
        updatedAt: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加仓库基础信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getWarehouse(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改仓库基础信息"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateWarehouse(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addWarehouse(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除仓库基础信息编号为"' + ids + '"的数据项？').then(function () {
        return delWarehouse(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('storage/warehouse/export', {
        ...this.queryParams
      }, `warehouse_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
